package cn.terys.terystransactionclient.data;

import android.content.Context;
import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public final class BarcodeManager
{

    private BarcodeManager()
    {
    }

    public static Bitmap createQrCodeBitmap(Context context, String str, int widthPixel, int heightPixel) throws CodeException
    {
        try
        {
            BitMatrix matrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, widthPixel, heightPixel);
            int width = matrix.width;
            int height = matrix.height;
            int[] pixels = new int[width * height];
            for (int y = 0; y < width; ++y)
            {
                for (int x = 0; x < height; ++x)
                {
                    if (matrix.get(x, y))
                    {
                        pixels[y * width + x] = 0xff000000; // black pixel
                    } else
                    {
                        pixels[y * width + x] = 0xffffffff; // white pixel
                    }
                }
            }
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.setPixels(pixels, 0, width, 0, 0, width, height);
            return bmp;
        } catch (WriterException e)
        {
            throw new CodeException(context, CodeException.QRCODE_CREATEERROR_CODE, e);
        }
    }

}
